package dao.impl;

import dao.TaskDAO;
import domain.Task;
import org.eclipse.persistence.config.HintValues;
import org.eclipse.persistence.config.QueryHints;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import util.DateComparator;
import util.SortedList;

import javax.persistence.*;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: Алексей
 * Date: 03.03.13
 * Time: 19:06
 * To change this template use File | Settings | File Templates.
 */
@Repository
@Transactional
public class TaskDAODB implements TaskDAO {

    @PersistenceContext
    private EntityManager em;

    private List<Task> tasks;

    public TaskDAODB(){
        /*tasks = new SortedList<Task>(new DateComparator());
        Query query = em.createQuery("select t from Task t");
        for (Task task : (List<Task>)query.getResultList())
            tasks.add(task);*/
    }

    @Override
    public List<Task> getAllTasks() {
        return tasks;
    }

    @Override
    public Task getTask(int id) {
        for (Task task : tasks) {
            if (task.getId() == id) return task;
        }
        return null;
    }

    @Override
    public void refresh() {
        Query query = em.createQuery("select t from Task t").setHint(QueryHints.REFRESH, HintValues.TRUE);
        tasks.clear();
        for (Task task : (List<Task>)query.getResultList())
            tasks.add(task);
    }

    @Override
    public Task getTaskFromStorage(int id) {
        Query query = em.createQuery("select t from Task t where t.id = :id").setHint(QueryHints.REFRESH, HintValues.TRUE);
        query.setParameter("id", id);
        if (query.getResultList().size() != 0)
            return (Task)query.getResultList().get(0);
        return null;
    }

    @Override
    public void add(Task task) {
        em.persist(task);
        tasks.add(task);
    }

    @Override
    public void update(int id, Task task) {
        em.merge(task);
        int i = 0;
        for (Task oldTask : tasks) {
            if (oldTask.getId() == id) {
                tasks.remove(i);
                tasks.add(task);
                break;
            }
            i++;
        }
    }

    @Override
    public void delete(int id) {
        Query query = em.createQuery("delete from Task t WHERE t.id = :id");
        query.setParameter("id", id);
        query.executeUpdate();
        int i = 0;
        for (Task oldTask : tasks) {
            if (oldTask.getId() == id) {
                tasks.remove(i);
                break;
            }
            i++;
        }
    }

    public List<Task> getTasksFromDB(){
        Query query = em.createQuery("select t from Task t");
        return query.getResultList();
    }
}
